<template>
	<checkbox-group class="van-checkbox-group" :value="val" :disabled="props.disabled" @change="handleChange">
		<slot></slot>
	</checkbox-group>
</template>

<script setup>
	import {
		ref,
		watch,
		provide
	} from 'vue';

	const emit = defineEmits(['update:modelValue']);
	const props = defineProps({
		modelValue: {
			type: Array,
			default: () => []
		},
		disabled: {
			type: Boolean,
			default: false
		}
	});

	const val = ref(props.modelValue || []);
	const all = ref([]);

	watch(() => val.value, (newValue) => {
		emit('update:modelValue', newValue);
	});

	watch(() => props.modelValue, (newValue) => {
		val.value = newValue;
	});
	const setAll = (item) => {
		if (!all.value.includes(item)) {
			all.value.push(item);
		}
	};
	const toggleAll = (ob) => {
		if (!ob || !ob.checked) {
			val.value = [];
		} else {
			val.value = [...all.value];
		}
	}
	provide('checkboxGroup', {
		val,
		disabled: props.disabled,
		setAll,
		toggleAll
	});
	defineExpose({
		toggleAll
	})
	const handleChange = (e) => {
		val.value = e.detail.value;
	};
</script>

<style lang="scss" scoped>
</style>